// pages/record/index.js
import * as echarts from '../../dist/ec-canvas/echarts';
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        ec: {
            lazyLoad: true,
        },
        ecSpot: {
            lazyLoad: true,
        },
        circle: {
            size: 65,
            strokeWidth: 5,
            sAngle: 180
        },
        spot: {
            size: 100,
            strokeWidth: 8,
            sAngle: 180
        },
        type: 0,
        listDataTotal: {
            total: 0,
            processing: 0, //进行中
            finished: 0, //已完成
            discontinue: 0, //中止
            overtime: 0, //逾期
            due: 0, //预期
        },
        listData: {
            3: {
                name: '计划管理',
                total: 0,
                processing: 0,
                finished: 0,
                discontinue: 0,
                overtime: 0,
                due: 0,
            },
            1: {
                name: '活动管理',
                total: 0,
                processing: 0,
                finished: 0,
                discontinue: 0,
                overtime: 0,
                due: 0,
            },
            2: {
                name: 'TC筹开店铺',
                total: 0,
                processing: 0,
                finished: 0,
                discontinue: 0,
                overtime: 0,
                due: 0,
            },
        },
        listSpotTotal: {
            spotDay: 0,
            spotArea: 0,
            adDay: 0
        },
        listSpot: {
            dayData: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
            data: {
                1: {
                    name: '固定点位',
                    type: 'line',
                    data: [],
                },
                2: {
                    name: '临时点',
                    type: 'line',
                    data: [],
                },
                3: {
                    name: '广告位',
                    type: 'line',
                    data: [],
                },
            }
        },
        hotList: [],
        hotIndex: 0,
        mostList: [],
        mostIndex: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let _this = this;
        var user = wx.getStorageSync('user');
        _this.initLogin();
        console.log(user)
        if (user.isManager == 1) {
            _this.setData({
                navrole: 1
            })
        } else {
            _this.setData({
                navrole: 0
            })
        }
        setTimeout(function () {
            _this.init();
            // _this.initSpot();
        }, 100);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    init: function () {
        var _this = this;
        this.echartsComponnet = this.selectComponent('#mychart-dom-pie');
        this.echartsComponnet.init((canvas, width, height, dpr) => {
            // 初始化图表
            const Chart = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr
            });
            _this.getOption(Chart);
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return Chart;
        });
    },
    initSpot: function () {
        var _this = this;
        this.echartsComponnetSpot = this.selectComponent('#mychartSpot');
        this.echartsComponnetSpot.init((canvas, width, height, dpr) => {
            // 初始化图表
            const ChartSpot = echarts.init(canvas, null, {
                width: width,
                height: height,
                devicePixelRatio: dpr
            });
            _this.getSpotOption(ChartSpot);
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return ChartSpot;
        });
    },
    getOption(chart) {
        var _this = this;
        app.api.getProjectCount(function (res) {
            let params = res.data || [];
            let list = _this.data.listData;
            let data = [{
                    name: '执行数',
                    value: params != '' ? params.total.processing : 0
                },
                {
                    name: '中止数',
                    value: params != '' ? params.total.discontinue : 0
                },
                {
                    name: '完成数',
                    value: params != '' ? params.total.finished : 0
                },
            ];

            for (let index in list) {
                if (params[index]) {
                    list[index] = params[index];
                }
                switch (parseInt(index)) {
                    case 1:
                        list[index]['name'] = '活动管理';
                        break;
                    case 2:
                        list[index]['name'] = 'TC筹开店铺';
                        break;
                    case 3:
                        list[index]['name'] = '计划管理';
                        break;
                }

                list[index]['percentFinished'] = parseInt(list[index].finished / list[index].total * 100) || 0; //完成
                list[index]['percentDiscontinue'] = parseInt(list[index].discontinue / list[index].total * 100) || 0; //中止
                list[index]['percentOvertime'] = parseInt(list[index].overtime / list[index].total * 100) || 0; //逾期
            }

            // 执行数,中止数,完成数
            _this.setData({
                listData: list
            })

            var optoin = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}({c})\n{d}%',
                },
                backgroundColor: "#ffffff",
                color: ["#75c9e2", "#6699ff", "#3f83a6"],
                legend: {
                    bottom: 0,
                    left: 'center',
                    icon: 'circle',
                    textStyle: {
                        lineHeight: 0,
                    }
                },
                series: [{
                    label: {
                        normal: {
                            show: true,
                            fontSize: 14,
                            formatter(params) {
                                return params.name + '(' + params.data.value + ')\n' + parseInt(params.percent) + '%';
                            }
                        },
                    },
                    type: 'pie',
                    center: ['50%', '45%'],
                    radius: ['25%', '45%'],
                    data: data
                }]
            };

            chart.setOption(optoin);
        });
    },
    getSpotOption(chart) {
        var _this = this;

        let timestamp = Date.parse(new Date());
        let date = new Date(timestamp);
        //获取年份  
        let y = date.getFullYear();

        app.api.getPhpMini(res => {
            let data = res.data;
            console.log(res);

            let budget = [];
            // 预算达成率
            let list = _this.data.listSpot.data;
            for (let index in list) {
                list[index]['data'] = data.list[index];
                budget.push(list[index]);
            }
            console.log('budget', budget);

            _this.setData({
                ['listSpotTotal.spotDay']: data.manage.spotDay || 0, // 使用率
                ['listSpotTotal.spotArea']: data.manage.spotArea || 0, // 使用率
                ['listSpotTotal.adDay']: data.manage.adDay || 0, // 使用率
                ['listSpot.data.1.data']: data.list[1], // 固定预算率
                ['listSpot.data.2.data']: data.list[2], // 临时预算率
                ['listSpot.data.3.data']: data.list[3], // 广告预算率
                hotList: data.hot,
                mostList: data.most,
            })

            var optoin = {
                title: {
                    text: '当年累积预算达成率',
                    left: 'center',
                    top: 25,
                    textStyle: {
                        fontSize: 14,
                    }
                },
                color: ["#ccccff", "#007dc0", "#66cccc"],
                legend: {
                    bottom: 5,
                    left: 'center',
                    icon: 'rect',
                    textStyle: {
                        fontSize: 12,
                    },
                    itemHeight: 10,
                },
                grid: {
                    containLabel: true,
                    left: '10',
                    height: '66%'
                },
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    formatter: "{a0}: {c0}%\n{a1}: {c1}%\n{a2}: {c2}%"
                },
                xAxis: {
                    name: '月', // 给X轴加单位
                    type: 'category',
                    boundaryGap: false,
                    data: _this.data.listSpot.dayData,
                },
                yAxis: {
                    x: 'center',
                    type: 'value',
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    max: 100,
                    axisLabel: {
                        formatter: '{value} %',
                    },
                },
                series: budget,
                animationDelay: function (idx) {
                    return idx * 50;
                },
                animationEasing: 'elasticOut'
            };
            console.log(optoin)
            chart.setOption(optoin);
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    goNav: function (e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            type: index
        })
        this.getLoadChart(index, 10);
    },
    goHot: function (e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            hotIndex: index,
        })
        let type = this.data.type;
        this.getLoadChart(type, 10);
    },
    goMost: function (e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            mostIndex: index,
        })
        let type = this.data.type;
        this.getLoadChart(type, 10);
    },
    getLoadChart(type, time) {
        let _this = this;
        let num = parseInt(type);
        setTimeout(() => {
            switch (num) {
                case 1:
                    _this.initSpot();
                    break;
                default:
                    _this.init();
                    break;
            }
        }, time);
    },
    initLogin: function () {
        var that = this;
        wx.login({
            success(res) {
                if (res.code) {
                    var data = {
                        code: res.code
                    };
                    app.api.authorize(data).then(function (res) {
                        console.log("查看token:")
                        console.log(res)
                        if (res.code == 200) {
                            // 已授权，用token获取个人信息
                            wx.setStorageSync('token', res.data.access_token);
                            app.api.userDetail(function (res) {
                                that.setData({
                                    navrole: res.data.isManager == 1 ? 1 : 0
                                })
                            });
                        }
                    })
                } else {
                    console.log('登录失败！' + res.errMsg)
                    return false;
                }
            }
        })
    },
})